import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'

@Catch()
export class HttpExceptionFilter<T> implements ExceptionFilter {
  catch(exception: HttpException | any, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const request = ctx.getRequest<Request>() // 获取Request对象
    const url = request.url // 获取当前请求的URL
    let status = HttpStatus.INTERNAL_SERVER_ERROR
    let message = ''
    let errorResponse: any
    console.log(`Error occurred at URL: ${url}`, message, '0000') // 打印错误发生的URL
    if (exception instanceof HttpException) {
      status = exception.getStatus()
      const exceptionResponse: any = exception.getResponse()
      let validMessage = ''
      // 对于 HttpException 类型的异常，提取有效的错误信息
      if (typeof exceptionResponse === 'object') {
        validMessage = typeof exceptionResponse.message === 'string' ? exceptionResponse.message : exceptionResponse.message[0]
      }
      message = validMessage || exception.message
    } else if (exception instanceof Error){
      message = exception.message;
    }
    else {
      // 对于非 HttpException 类型的异常，打印堆栈信息并设置通用错误消息
      console.error('Unexpected error occurred:', exception.stack)
      message = 'An unexpected error occurred on the server.'
    }

    errorResponse = {
      data: {},
      message,
      code: -1
    }

    response.status(status)
    response.header('Content-Type', 'application/json; charset=utf-8')
    response.send(errorResponse)
  }
}
